<!--
 * @Author: 四川华西绿舍建材有限公司
 * @Date: 2024-03-02 23:20:02
 * @LastEditors: 陈波
 * @LastEditTime: 2024-03-04 22:35:29
 * @Description: 
 * @FilePath: \graDesign\src\views\UserInfo\components\PasswordPane.vue
-->
<template>
  <div>
    <el-form
      ref="ruleFormRef"
      :model="ruleForm"
      :rules="rules"
      label-width="120px"
      class="demo-ruleForm"
      status-icon
    >
      <el-form-item label="原密码" prop="oldPwd">
        <el-input
          type="password"
          v-model="ruleForm.oldPwd"
          show-password
          clearable
        />
      </el-form-item>
      <el-form-item label="新密码" prop="newPwd">
        <el-input
          type="password"
          v-model="ruleForm.newPwd"
          show-password
          clearable
        />
      </el-form-item>
      <el-form-item label="确认新密码" prop="ensureNewPwd">
        <el-input
          type="password"
          v-model="ruleForm.ensureNewPwd"
          show-password
          clearable
        />
      </el-form-item>
      <el-form-item class="btns">
        <span class="dialog-footer">
            <el-button @click="resetRuleForm(ruleFormRef)">重 置</el-button>
            <el-button type="success" @click="ensureUpdate(ruleFormRef)">确 定</el-button>
        </span>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, inject } from "vue";
import type { FormInstance, FormRules } from "element-plus";
// utils
import { checkPassword } from "@/utils/util";
// api
import editUserApi from "@/request/api/user";
// store
import useLoginStore from "@/store/login";
import { showMessageBox } from "@/utils/alertMsg";

const loginStore = useLoginStore();
// 刷新子路由
const reload: Function = inject('reload');

interface RuleForm {
  oldPwd: string
  newPwd: string
  ensureNewPwd: string
}

const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  oldPwd: '',
  newPwd: '',
  ensureNewPwd: '',
});

// 自定义校验
const validatePass = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请输入新密码"));
  } else {
    if (ruleForm.ensureNewPwd !== "") {
      if (!ruleFormRef.value) return;
      ruleFormRef.value.validateField("checkPass", () => null);
    }
    // 校验密码
    if (!checkPassword(value)) {
      callback(
        new Error("密码格式错误，密码由数字、字母以及特殊字符组成且长度最少5位")
      );
    }
    callback();
  }
};
const validatePass2 = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error("请再次输入密码"));
  } else if (value !== ruleForm.newPwd) {
    callback(new Error("两次密码不一致"));
  } else {
    callback();
  }
};

// 校验规则
const rules = reactive<FormRules<RuleForm>>({
  oldPwd: [{ message: "请输入旧密码！！！", required: true, trigger: "blur" }],
  newPwd: [{ validator: validatePass, required: true, trigger: "blur" }],
  ensureNewPwd: [{ validator: validatePass2, required: true, trigger: "blur" }],
});

// 重置
const resetRuleForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
}


/**
 * defineEmits emit给父组件
 */
interface EmitEvent {
  (e: "closeDialog"): void;
}
const emit = defineEmits<EmitEvent>();
const close = () => {
  emit("closeDialog");
};

const ensureUpdate = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      editUserApi.updateUserPassword(ruleForm).then((res: any) => {
        if (res.code === 200) {
          showMessageBox('success', res.msg, 3000, false)
          loginStore.getAndSetUserInfo()
          close();
          setTimeout(() => {
            reload();
          }, 500);
        } else {
          showMessageBox('error', res.msg, 3000, false)
        }
      })
    } else {
      console.log('invalid')
    }
  })
}

</script>

<style scoped lang="scss">
</style>
